package cool.tsy.emos.wx.config.xss;

import cn.hutool.http.HtmlUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.util.StringUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author: hongxuan.wang
 * @date: Created in 2021/9/24 16:29
 * @description: 覆盖 HttpServletRequest 方法，抵御 xss 跨站脚本攻击
 * @mail: 1443424326@qq.com
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String getParameter(String name) {
        String value = super.getParameter(name);
        if (!StringUtils.isEmpty(value)) {
            // 对字符串进行转义
            value = HtmlUtil.filter(value);
        }
        return value;
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(name);
        if (values != null) {
            values = Arrays.stream(values).map(
                    value -> {
                        if (!StringUtils.isEmpty(value)) {
                            value = HtmlUtil.filter(value);
                            System.out.println(value);
                        }
                        return value;
                    }
            ).toArray(String[]::new);
        }
        return values;
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> parameterMap = super.getParameterMap();
        LinkedHashMap<String, String[]> map = new LinkedHashMap<>();
        if (parameterMap != null) {
            for (String key : parameterMap.keySet()) {
                String[] values = parameterMap.get(key);
                if (values != null) {
                    values = (String[]) Arrays.stream(values).map(
                            value -> {
                                if (!StringUtils.isEmpty(value)) {
                                    value = HtmlUtil.filter(value);
                                }
                                return value;
                            }
                    ).toArray();
                }
                map.put(key, values);
            }
        }
        return map;
    }

    @Override
    public String getHeader(String name) {
        String value = super.getHeader(name);
        if (!StringUtils.isEmpty(value)) {
            value = HtmlUtil.filter(value);
        }
        return value;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        ServletInputStream inputStream = super.getInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        BufferedReader buffer = new BufferedReader(reader);
        StringBuilder builder = new StringBuilder();

        String line = buffer.readLine();
        while (line != null) {
            builder.append(line);
            line = buffer.readLine();
        }

        buffer.close();
        reader.close();
        inputStream.close();

        Map<String, Object> map = JSONUtil.parseObj(builder.toString());
        Map<String, Object> result = new LinkedHashMap<>();

        if (map != null) {
            for (String key : map.keySet()) {
                Object value = map.get(key);
                if (value instanceof String) {
                    if (!StringUtils.isEmpty(value.toString())) {
                       result.put(key, HtmlUtil.filter(value.toString()));
                    }
                } else {
                    result.put(key, value);
                }
            }
        }

        String json = JSONUtil.toJsonStr(result);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(json.getBytes());
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
    }
}
